<template>
  <div>
    <button id="openModal" @click="showAuthModal">登录/注册</button>

    <!-- 登录/注册弹窗 -->
    <div class="modal-overlay" v-show="authModalVisible" @click.self="hideAuthModal">
      <div class="auth-container">
        <button class="close-btn" @click="hideAuthModal">×</button>
        <div class="auth-forms" :style="{ transform: `translateX(${currentForm === 'login' ? 0 : -400}px)` }">
          
          <!-- 登录表单 -->
          <div class="auth-form">
            <div class="auth-header">
              <h2>欢迎回来</h2>
              <p>请登录您的账号</p>
            </div>
            <form @submit.prevent="handleLogin">
              <div class="form-group">
                <label for="loginUsername">账号</label>
                <input 
                  type="text" 
                  id="loginUsername" 
                  v-model="loginForm.userAccount" 
                  placeholder="请输入您的账号" 
                  required
                  @input="checkAccountForSms"
                >
              </div>
              <div class="form-group">
                <label for="loginPassword">密码</label>
                <input 
                  type="password" 
                  id="loginPassword" 
                  v-model="loginForm.password" 
                  placeholder="请输入您的密码" 
                  required
                >
              </div>
              <div class="form-group">
                <label for="loginCode">短信验证码</label>
                <div class="code-input-group">
                  <input 
                    type="text" 
                    id="loginCode" 
                    v-model="loginForm.smsCode" 
                    placeholder="请输入短信验证码" 
                  >
                  <button 
                    type="button" 
                    class="send-code-btn" 
                    @click="sendLoginSmsCode"
                    :disabled="!canSendSms || loginCountdown > 0"
                  >
                    {{ loginCountdown > 0 ? `${loginCountdown}s后重新获取` : '获取验证码' }}
                  </button>
                </div>
              </div>
              <button type="submit" class="submit-btn">登录</button>
            </form>
            <div class="switch-form">
              还没有账号？<a @click="switchToRegister">立即注册</a>
            </div>
          </div>
          
          <!-- 注册表单 -->
          <div class="auth-form">
            <div class="auth-header">
              <h2>创建账号</h2>
              <p>加入我们，开始您的旅程</p>
            </div>
            <form @submit.prevent="handleRegister">
              <div class="form-group">
                <label for="registerUsername">账号</label>
                <input 
                  type="text" 
                  id="registerUsername" 
                  v-model="registerForm.userAccount" 
                  placeholder="请输入您的账号" 
                  required
                >
              </div>
              <div class="form-group">
                <label for="registerPhone">手机号</label>
                <div class="code-input-group">
                  <input 
                    type="tel" 
                    id="registerPhone" 
                    v-model="registerForm.userPhone" 
                    placeholder="请输入您的手机号" 
                    required
                  >
                  <button 
                    type="button" 
                    class="send-code-btn" 
                    @click="sendRegisterSmsCode"
                    :disabled="registerCountdown > 0"
                  >
                    {{ registerCountdown > 0 ? `${registerCountdown}s后重新获取` : '获取验证码' }}
                  </button>
                </div>
              </div>
              <div class="form-group">
                <label for="registerCode">短信验证码</label>
                <input 
                  type="text" 
                  id="registerCode" 
                  v-model="registerForm.smsCode" 
                  placeholder="请输入短信验证码" 
                  required
                >
              </div>
              <div class="form-group">
                <label for="registerPassword">密码</label>
                <input 
                  type="password" 
                  id="registerPassword" 
                  v-model="registerForm.password" 
                  placeholder="请输入您的密码" 
                  required
                >
              </div>
              <div class="form-group">
                <label for="registerConfirmPassword">确认密码</label>
                <input 
                  type="password" 
                  id="registerConfirmPassword" 
                  v-model="registerForm.confirmPassword" 
                  placeholder="请再次输入您的密码" 
                  required
                >
              </div>
              <button type="submit" class="submit-btn">注册</button>
            </form>
            <div class="switch-form">
              已有账号？<a @click="switchToLogin">立即登录</a>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 调查问卷组件 -->
    <Questionnaire 
      v-if="surveyModalVisible"
      @submit="handleSurveySubmit"
      @skip="handleSurveySkip"
      @close="surveyModalVisible = false"
    />
  </div>
</template>

<script>
import Questionnaire from './Questionnaire.vue'

export default {
  name: 'Login',
  components: {
    Questionnaire
  },
  data() {
    return {
      authModalVisible: false,
      surveyModalVisible: false,
      currentForm: 'login',
      canSendSms: false,
      loginForm: {
        userAccount: '',
        password: '',
        smsCode: ''
      },
      registerForm: {
        userAccount: '',
        userPhone: '',
        smsCode: '',
        password: '',
        confirmPassword: ''
      },
      questionnaireData: {
      },
      loginCountdown: 0,
      registerCountdown: 0,
      loginCountdownInterval: null,
      registerCountdownInterval: null,
      scrollPosition: 0 // 新增：记录滚动位置
    }
  },
  methods: {
    showAuthModal() {
      // 记录当前滚动位置
      this.scrollPosition = window.pageYOffset || document.documentElement.scrollTop
      // 禁止滚动
      document.body.style.overflow = 'hidden'
      document.body.style.position = 'fixed'
      document.body.style.top = `-${this.scrollPosition}px`
      document.body.style.width = '100%'
      
      this.authModalVisible = true
      this.currentForm = 'login'
    },
    hideAuthModal() {
      // 恢复滚动
      document.body.style.overflow = ''
      document.body.style.position = ''
      document.body.style.top = ''
      document.body.style.width = ''
      // 恢复滚动位置
      window.scrollTo(0, this.scrollPosition)
      
      this.authModalVisible = false
    },
    switchToRegister() {
      this.currentForm = 'register'
    },
    switchToLogin() {
      this.currentForm = 'login'
    },
    checkAccountForSms() {
      this.canSendSms = this.loginForm.userAccount.length > 0
    },
    handleLogin() {
      const { userAccount, password, smsCode } = this.loginForm
      
      if(!userAccount || !password) {
        this.$centerMessage({
          message: '账号和密码为必填项！\u00A0\u00A0\u00A0',
          type: 'warning'
        });
        return
      }
      
      if(smsCode && smsCode !== '15160239910') {
        this.$centerMessage({
          message: '短信验证码错误！\u00A0\u00A0\u00A0',
          type: 'warning'
        });
        return
      }
      
      this.$api.serviceUser.post('api/user/login', this.loginForm, {
        headers: { 'Content-Type': 'application/json' }
      })
      .then(response => {
        const userLoginVo = response.data; 
        
        if (userLoginVo.code == 40903 || userLoginVo.code == 40904) {
          this.$centerMessage({
            message: userLoginVo.message,
            type: 'warning'
          });
          
          return
        }

        this.$store.dispatch('user/login', userLoginVo)
        
        this.$centerMessage({
        message: `欢迎回来，${userLoginVo.data.userAccount}！登录成功！\u00A0\u00A0\u00A0`,
        type: 'success'
      });
        
        this.authModalVisible = false
        this.loginForm = { userAccount: '', password: '', smsCode: '' }
      })
      .catch(error => {
        console.error('登录失败:', error.response?.data || error.message);
      });      
    },
    handleRegister() {
      const { userAccount, userPhone, smsCode, password, confirmPassword } = this.registerForm
      
      if(!userAccount || !userPhone || !smsCode || !password || !confirmPassword) {
        this.$centerMessage({
          message: '请填写所有必填字段！\u00A0\u00A0\u00A0',
          type: 'warning'
        });
        return
      }
      
      if(!/^1[3-9]\d{9}$/.test(userPhone)) {
        this.$centerMessage({
          message: '请输入有效的手机号码！\u00A0\u00A0\u00A0',
          type: 'warning'
        });
        return
      }
      
      if (password !== confirmPassword) {
        this.$centerMessage({
          message: '两次输入的密码不一致！\u00A0\u00A0\u00A0',
          type: 'warning'
        });
        return
      }
      
      if (password.length < 6) {
        this.$centerMessage({
          message: '密码长度不能少于6位！\u00A0\u00A0\u00A0',
          type: 'warning'
        });
        return
      }
      
      if (smsCode !== '15160239910') {
        this.$centerMessage({
          message: '短信验证码错误！\u00A0\u00A0\u00A0',
          type: 'warning'
        });
        return
      }
      
      this.$api.serviceUser.post('api/user/register', this.registerForm, {
        headers: { 'Content-Type': 'application/json' }
      })
      .then(response => {
        const responseData = response.data; 
        
        console.log('注册结果:', responseData);
        if (responseData.code == 40901 || responseData.code == 40902) {
          this.$centerMessage({
            message: responseData.message,
            type: 'warning'
          });
          
          return
        }

        this.$centerMessage({
        message: `注册成功，${userAccount}！欢迎加入我们！\u00A0\u00A0\u00A0`,
          type: 'success'
        });
        
        this.authModalVisible = false
        
        this.$nextTick(() => {
          this.surveyModalVisible = true
        })
      })
      .catch(error => {
        console.error('注册失败:', error.response?.data || error.message);
        this.$message.error(error.response?.data?.message || '注册失败');
      });
    },
    sendLoginSmsCode() {
      const { userAccount } = this.loginForm
      
      if (!userAccount) {
        this.$centerMessage({
          message: '请先输入账号',
          type: 'success'
        });
        return
      }
      
      this.$centerMessage({
        message: `验证码已发送至 ${userAccount} 绑定的手机号，示例验证码：15160239910\u00A0\u00A0\u00A0`,
        type: 'success'
      });
      this.startLoginCountdown()
    },
    sendRegisterSmsCode() {
      const { userPhone } = this.registerForm
      
      if (!userPhone) {
        this.$centerMessage({
          message: '请输入手机号码！\u00A0\u00A0\u00A0',
          type: 'warning'
        });
        return
      }
      
      if (!/^1[3-9]\d{9}$/.test(userPhone)) {
        this.$centerMessage({
          message: '请输入有效的手机号码！\u00A0\u00A0\u00A0',
          type: 'warning'
        });
        return
      }
      
      this.$centerMessage({
        message: `注册验证码已发送至 ${userPhone}，示例验证码：15160239910\u00A0\u00A0\u00A0`,
        type: 'success'
      });
      this.startRegisterCountdown()
    },
    startLoginCountdown() {
      this.loginCountdown = 60
      this.loginCountdownInterval = setInterval(() => {
        this.loginCountdown--
        if (this.loginCountdown <= 0) {
          clearInterval(this.loginCountdownInterval)
        }
      }, 1000)
    },
    startRegisterCountdown() {
      this.registerCountdown = 60
      this.registerCountdownInterval = setInterval(() => {
        this.registerCountdown--
        if (this.registerCountdown <= 0) {
          clearInterval(this.registerCountdownInterval)
        }
      }, 1000)
    },
    handleSurveySubmit(categories) {
      if(categories.length > 0) {
        this.$centerMessage({
          message: '已保存您的兴趣选择：\n' + categories.join(', ') + "\u00A0\u00A0\u00A0",
          type: 'success'
        });
      } else {
        this.$centerMessage({
          message: '您未选择任何类别\u00A0\u00A0\u00A0',
          type: 'success'
        });
      }
      console.log(categories);

      this.questionnaireData.categories = categories
      this.questionnaireData.userAccount = this.registerForm.userAccount
      this.questionnaireData.userPhone = this.registerForm.userPhone
      this.sendQuestionnaire(this.questionnaireData)

      this.surveyModalVisible = false
    },
    handleSurveySkip(categories) {
      this.$centerMessage({
        message: '已跳过兴趣调查\u00A0\u00A0\u00A0',
        type: 'success'
      });
      console.log(categories);

      this.questionnaireData.categories = categories
      this.questionnaireData.userAccount = this.registerForm.userAccount
      this.questionnaireData.userPhone = this.registerForm.userPhone
      this.sendQuestionnaire(this.questionnaireData)

      this.surveyModalVisible = false
    },
    sendQuestionnaire(questionnaireData) {
      try {
        const response = this.$api.serviceUser.post('api/user/questionnaire', JSON.stringify(questionnaireData), {
        headers: {
          'Content-Type': 'application/json',  // 必须设置
        },
        });
        console.log('提交兴趣表单成功:', response);
        } catch (error) {
          console.error('提交兴趣表单失败:', error);
      } finally {
        this.registerForm = { 
          userAccount: '', 
          userPhone: '', 
          smsCode: '',
          password: '', 
          confirmPassword: '' 
        }
      }
    },
  },
  mounted() {
    document.addEventListener('keydown', (e) => {
      if(e.key === 'Escape') {
        this.hideAuthModal()
      }
    })
  },
  beforeDestroy() {
    if (this.loginCountdownInterval) {
      clearInterval(this.loginCountdownInterval)
    }
    if (this.registerCountdownInterval) {
      clearInterval(this.registerCountdownInterval)
    }
    document.removeEventListener('keydown', () => {})
  }
}
</script>

<style scoped>
/* 原有样式完全保持不变 */
#openModal {
  background-color: transparent;
  border: 1px solid #ddd;
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

#openModal:hover {
  border-color: #ff4d4f;
  color: #ff4d4f;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.auth-container {
  width: 400px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  position: relative;
}

.auth-forms {
  display: flex;
  width: 800px;
  transition: transform 0.5s ease-in-out;
}

.auth-form {
  width: 400px;
  padding: 25px;
}

.auth-header {
  text-align: center;
  margin-bottom: 15px;
}

.auth-header h2 {
  color: #333;
  font-size: 20px;
  margin-bottom: 5px;
}

.auth-header p {
  color: #666;
  font-size: 14px;
}

.form-group {
  margin-bottom: 12px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  color: #555;
  font-size: 14px;
}

.form-group input {
  width: 91%;
  padding: 10px 13px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-group input:focus {
  border-color: #ff4d4f;
  outline: none;
}

.submit-btn {
  width: 100%;
  padding: 10px;
  background-color: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-btn:hover {
  background-color: #ff7875;
}

.switch-form {
  text-align: center;
  margin-top: 12px;
  color: #666;
  font-size: 14px;
}

.switch-form a {
  color: #ff4d4f;
  text-decoration: none;
  font-weight: bold;
  cursor: pointer;
  font-size: 14px;
}

.switch-form a:hover {
  text-decoration: underline;
}

.close-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 25px;
  height: 25px;
  background: none;
  border: none;
  font-size: 26px;
  color: #999;
  cursor: pointer;
  z-index: 10;
}

.close-btn:hover {
  color: #ff4d4f;
}

.code-input-group {
  display: flex;
  gap: 10px;
}

.code-input-group input {
  flex: 1;
  min-width: 0;
}

.send-code-btn {
  width: 120px;
  padding: 10px;
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  border-radius: 4px;
  color: #666;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap;
}

.send-code-btn:hover:not(:disabled) {
  background-color: #ff4d4f;
  color: white;
  border-color: #ff4d4f;
}

.send-code-btn:disabled {
  cursor: not-allowed;
  opacity: 0.7;
}

@media (max-width: 480px) {
  .auth-container {
    width: 90%;
    margin: 0 auto;
  }
  
  .auth-forms {
    width: 180%;
  }
  
  .auth-form {
    width: 90%;
    padding: 20px;
  }
  
  .code-input-group {
    flex-direction: column;
    gap: 8px;
  }
  
  .send-code-btn {
    width: 100%;
  }
}
</style>